<!-- 学社 - 成员 - 成员列表 -->
<template>
  <z-paging-list ref="list" v-model="state.list" :safe-area-inset-bottom="false"
    :refresher-enabled="state.tabCurrent == 0" :loading-more-enabled="state.tabCurrent == 0"
    :hide-empty-view="state.tabCurrent == 1" @loadData="loadData">
    <template #top>
      <z-navbar title="成员" :border-bottom="true" bg-color="#F4AE20"></z-navbar>
    </template>
    <view class="px-4 py-5">
      <!-- 社长/管理员身份 -->
      <template v-if="state.member_position >= 2">
        <!-- tab栏 -->
        <view class="flex mx-auto w-344 h-48 bg-#F6F6F6 rounded-md mb-3">
          <view v-for="(item, index) in tabList" :key="index" :class="[state.tabCurrent == index ? 'tab-active' : '']"
            class="flex-1 leading-6 text-center c-#999 text-28" @click="onTabChage(index)">
            {{ item.label }}
          </view>
        </view>
      </template>
      <!-- 其他身份 -->
      <!-- TODO:列表空状态显示 -->
      <view v-if="state.member_position >= 2 && state.tabCurrent == 0">
        <view v-for="(item, index) in state.list" :key="index" class="flex items-center py-2">
          <u-image width="60" height="60" border-radius="60"
            :src="item.user?.avatar ?? '/static/images/user/ic_def_avatar.png'" class="mr-4 flex-shrink-0"
            @click="toHomePage(item.user_id)" />
          <view class="flex-1 c-#333 text-28 text-single font-bold" @click="toHomePage(item.user_id)">{{
            item.user?.nickname }}</view>
          <view class="flex-shrink-0 btn-audit" @click="onAudit(item)">审核</view>
        </view>
      </view>
      <view v-else>
        <template v-if="state.management.length > 0">
          <!--社长管理员-->
          <view class="c-#999 text-28 mb-1">
            社长、管理员({{ state.management.length }}人)
          </view>
          <member-item v-for="(item, index) in state.management" :from-type="state.fromType" :key="index" :data="item"
            :is-creator="state.member_position == 3" :show-operate="true" :show-check="state.showCheck"
            @operate="onOperate" @selected="onSelected" />
        </template>
        <template v-if="state.counselor.length > 0">
          <!--顾问-->
          <view class="c-#999 text-28 my-1">
            顾问({{ state.counselor.length }}人)
          </view>
          <member-item v-for="(item, index) in state.counselor" :from-type="state.fromType" :key="index" :data="item"
            :is-creator="state.member_position == 3" :show-operate="true" :show-check="state.showCheck"
            @operate="onOperate" @selected="onSelected" />
        </template>
        <template v-if="state.member.length > 0">
          <!--成员-->
          <view class="c-#999 text-28 my-1">
            成员({{ state.member.length }}人)
          </view>
          <member-item v-for="(item, index) in state.member" :from-type="state.fromType" :key="index" :data="item"
            :is-creator="state.member_position == 3" :show-operate="true" :show-check="state.showCheck"
            @operate="onOperate" @selected="onSelected" />
        </template>
      </view>
    </view>
    <template #bottom>
      <view v-if="state.showCheck" class="h-150 bg-white">
        <u-line class="w-full" color="#eee" :hair-line="false" />
        <view class="flex items-center justify-between">
          <view class="flex items-center ml-4 h-80">
            <view @click="onSelectedAll" class="h-80 flex items-center">
              <u-checkbox :modelValue="state.selectedAll" shape="circle" active-color="#F4AF22" />
            </view>
            <view class="mr-1 c-#666 text-28">全选</view>
            <view class="c-#999 text-24">已选{{ selectNum }}位</view>
          </view>
          <view :class="['btn-submit w-400', selectNum > 0 ? 'opacity-100' : 'opacity-50']" @click="onSubmit">确认</view>
        </view>
      </view>
    </template>
  </z-paging-list>
  <!-- 操作弹窗 -->
  <u-modal v-model="state.showOperateModal" :show-title="false" border-radius="12" :show-cancel-button="false"
    :show-confirm-button="false">
    <view class="slot-content">
      <view @click="state.showOperateModal = false" class="absolute top-0 right-17 w-166 h-166 flex justify-end">
        <image class="mt-3 mr-2 w-22 h-22" src="/static/images/home/ic_delete.png" />
      </view>
      <view class="flex items-center justify-center py-2">
        <view class="flex flex-col justify-center items-center w-116">
          <view class="relative">
            <view class="w-116 h-116 rounded-full border-avatar">
              <u-image shape="circle" width="100%" height="100%"
                :src="state.oprateCurrentMember?.user?.avatar ?? '/static/images/user/ic_def_avatar.png'"></u-image>
            </view>
            <view v-if="state.oprateCurrentMember?.member_position > 0" class="label-style tag-identity"
              :class="`label-style${state.oprateCurrentMember?.member_position}`">{{ identity }}</view>
          </view>
          <view class="c-#666 text-28 mt-2  text-center w-full text-single">{{
            state.oprateCurrentMember?.user?.nickname ?? '-' }}</view>
        </view>
      </view>
      <view class="flex justify-between items-center pt-3 u-border-top">
        <view class="flex flex-col items-center">
          <view class="c-#666 text-28">{{ state.oprateCurrentMember?.join_day }}天</view>
          <view class="mt-1 c-#999 text-24">加入天数</view>
        </view>
        <view class="flex flex-col items-center">
          <view class="c-#666 text-28">{{ state.oprateCurrentMember?.dynamic_number }}条</view>
          <view class="mt-1 c-#999 text-24">动态</view>
        </view>
        <view class="flex flex-col items-center">
          <view class="c-#666 text-28">{{ state.oprateCurrentMember?.like_num }}次</view>
          <view class="mt-1 c-#999 text-24">获得赞同</view>
        </view>
      </view>
      <!-- 社长-成员详情 -->
      <view v-if="state.member_position == 3" class="px-4 py-1 mt-4 mb-5 bg-#F6F6F6">
        <view v-if="state.oprateCurrentMember?.name" class="c-#333 my-2 text-28 w-full text-single">姓名：{{
          state.oprateCurrentMember?.name }}</view>
        <view v-if="state.oprateCurrentMember?.wechat_code" class="c-#333 text-28 my-2 w-full text-single">微信号：{{
          state.oprateCurrentMember?.wechat_code }}</view>
        <view v-if="state.oprateCurrentMember?.company_name" class="c-#333 text-28 my-2 w-full text-single">公司名称：{{
          state.oprateCurrentMember?.company_name }}</view>
        <view v-if="state.oprateCurrentMember?.createtime"
          class="flex items-center c-#333 text-28 my-2 w-full text-single">加入时间：{{
            dateFormat(state.oprateCurrentMember?.createtime, 'YYYY-MM-DD') }}</view>
      </view>
      <!-- 非社长-本人详情+编辑信息 -->
      <view v-if="state.member_position != 3" class="px-4 py-1 mt-4 mb-5 bg-#F6F6F6">
        <view class="c-#333 text-28 w-full text-single" :class="[state.member_position != 3 ? 'flex items-center' : '']">
          姓名：
          <u-input class="flex-1" v-model="state.editForm.name" input-align="right" placeholder="请输入"
            :custom-style="inputStyle" :placeholder-style="placeholderStyle" :border="false" />
          <image class="ml-1 w-14 h-24" src="/package_society/static/images/ic_arrow_r.png">123</image>
        </view>
        <view class="c-#333 text-28 w-full text-single" :class="[state.member_position != 3 ? 'flex items-center' : '']">
          微信号：
          <u-input class="flex-1" v-model="state.editForm.wechat_code" input-align="right" placeholder="请输入"
            :custom-style="inputStyle" :placeholder-style="placeholderStyle" :border="false" />
          <image class="ml-1 w-14 h-24" src="/package_society/static/images/ic_arrow_r.png">123</image>
        </view>
        <view class="c-#333 text-28 w-full text-single" :class="[state.member_position != 3 ? 'flex items-center' : '']">
          公司名称：
          <u-input class="flex-1" v-model="state.editForm.company_name" input-align="right" placeholder="请输入"
            :custom-style="inputStyle" :placeholder-style="placeholderStyle" :border="false" />
          <image class="ml-1 w-14 h-24" src="/package_society/static/images/ic_arrow_r.png">123</image>
        </view>
        <view v-if="state.oprateCurrentMember?.createtime"
          class="flex items-center c-#333 text-28 my-2 w-full text-single"
          :class="[state.member_position != 3 ? 'justify-between' : '']">加入时间：<view class="flex-1 flex justify-end">{{
            dateFormat(state.oprateCurrentMember?.createtime, 'YYYY-MM-DD') }}</view>
        </view>
      </view>
      <!-- 社长显示的操作按钮 -->
      <view v-if="state.member_position == 3" class="flex items-center justify-center">
        <!-- 顾问不能设为管理员 -->
        <view class="btn btn-remove" @click="onRemove(state.oprateCurrentMember.id)">移出该成员</view>
        <view v-if="state.oprateCurrentMember?.member_position != 1" class="btn btn-manage ml-5"
          @click="onManage(state.oprateCurrentMember.id, state.oprateCurrentMember?.member_position)">
          {{ state.oprateCurrentMember?.member_position == 2 ? '取消管理员' : '设为管理员' }}
        </view>
      </view>
      <!-- 非社长显示的操作按钮 -->
      <view v-if="state.member_position != 3" class="flex items-center justify-center">
        <view class="btn btn-edit" @click="onEdit(state.oprateCurrentMember.club_id, state.oprateCurrentMember.id)">
          保存
        </view>
      </view>
    </view>
  </u-modal>
  <!-- 审核弹窗 -->
  <u-modal v-model="state.showAuditModal" :show-title="false" border-radius="12" :show-cancel-button="false"
    :show-confirm-button="false">
    <view class="slot-content">
      <view @click="state.showAuditModal = false" class="absolute top-0 right-17 w-166 h-166 flex justify-end">
        <image class="mt-3 mr-2 w-22 h-22" src="/static/images/home/ic_delete.png" />
      </view>
      <view class="flex items-center py-2">
        <u-image width="60" height="60" border-radius="60" :src="state.auditCurrentMember?.user?.avatar" class="mr-4" />
        <view class="flex-1 c-#333 text-28 text-single font-bold mr-2">{{ state.auditCurrentMember?.user?.nickname }}
        </view>
      </view>
      <view class="c-#333 text-28 my-5 w-full text-single">姓号：{{ state.auditCurrentMember?.name }}</view>
      <view class="c-#333 text-28 my-5 w-full text-single">微信号：{{ state.auditCurrentMember?.wechat_code }}</view>
      <view class="c-#333 text-28 mb-5 w-full text-single">公司名称：{{ state.auditCurrentMember?.company_name }}</view>
      <view class="c-#333 text-28 mb-8">备注：{{ state.auditCurrentMember?.remark }}</view>
      <view class="flex items-center justify-center">
        <view class="btn btn-remove" @click="onAuditHandle(2)">拒绝</view>
        <view class="btn btn-manage ml-5" @click="onAuditHandle(1)">通过</view>
      </view>
    </view>
  </u-modal>
</template>
<script setup>
import { dateFormat } from '@/common/util/date'
import { showToast } from '@/common/util/uni'
import { refreshPrePage, toHomePage, formatIdentity } from '@/common/util/util'
import { societyIdentity } from '@/common/constant/society.js'
import memberItem from '@/package_society/components/member/member-item.vue';
import { getMemberAuditLists, getMemberLists, postMemberAudit, postMemberSetAdministrator, postMemberCancelAdministrator, postMemberDel, getMemberModalDetail, postMemberProfile } from '@/common/http/module/society.js'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()
const list = ref();
const state = reactive({
  fromType: '', // work-学习成长 trend-动态
  editForm: {
    name: '',
    wechat_code: '',
    company_name: ''
  }, // 成员编辑表单
  club_id: '', // 学社id
  member_position: '', // 用户在该学社身份
  list: [], // 成员列表
  management: [], // 社长、管理员列表
  counselor: [], // 顾问列表
  member: [], // 成员列表,
  totalMemberList: [], // 所有成员列表
  call_ids: [], // 选中初始化成员id集合
  auditCurrentMember: '', // 当前审核人员信息
  oprateCurrentMember: '', // 当前操作人员信息,
  showOperateModal: false,
  showAuditModal: false,
  tabCurrent: 0, // tab当前激活项

  selectedAll: false, // 是否全选
  showCheck: false, //是否显示checkbox
  userId: 0,
  userType: 1,
  memberNum: 0,
});

// tab栏
const tabList = [
  {
    label: '待审核',
    value: 0
  },
  {
    label: '已审核',
    value: 1
  }
]
const placeholderStyle = "fontSize: '28rpx', color: '#999'"
const inputStyle = {
  color: '#333',
  fontSize: '28rpx',
}

const userInfo = computed(() => userStore.userInfo)
// 社长显示成员编辑按钮
// const showOperate = computed(() => state.member_position == 3)
// 学社身份中文名
const identity = computed(() =>state.oprateCurrentMember?.is_management?'客户经理': societyIdentity.find(v => v.value == state.oprateCurrentMember?.member_position)?.label)
// 选择成员数量
const selectNum = computed(() => state.totalMemberList.filter(v => v.selected).length)

// 监听单项选择
watch(() => selectNum.value, (val) => {
  state.selectedAll = val == state.totalMemberList.filter(v => {
    return state.fromType == 'work' ? v.member_position != 3 : v.user_id != userInfo.value.id
  }).length
})

// tab切换
function onTabChage (i) {
  state.tabCurrent = i
  // loadData()
  refresh()
}

async function onOperate (member) {
  console.log('onOperate', member);
  const { data } = await getMemberModalDetail(member.id, member.club_id)
  state.oprateCurrentMember = data
  state.editForm.name = data.name
  state.editForm.wechat_code = data.wechat_code
  state.editForm.company_name = data.company_name
  state.showOperateModal = true

}

// 选择
function onSelected (val, userId) {
  console.log('onSelected', val, userId);
  const totalMemberList = [...state.management, ...state.counselor, ...state.member].filter(v => {
    return state.fromType == 'work' ? v.member_position != 3 : v.user_id != userInfo.value.id
  })
  totalMemberList.forEach(v => {
    if (v.userId == userId) {
      v.selected = !v.selected
    }
  })
  state.totalMemberList = totalMemberList
}

// 移出
function onRemove (id) {
  postMemberDel({ member_id: id }).then(() => {
    showToast('移出成功')
    state.showOperateModal = false
    state.memberNum > 0 ? state.memberNum-- : 0
    loadData()
  })
}

// 设为管理员
function onManage (id, member_position) {
  const postMethod = member_position == 2 ? postMemberCancelAdministrator : postMemberSetAdministrator
  postMethod({ member_id: id }).then(() => {
    showToast(`${member_position == 2 ? '取消管理员成功' : '设为管理员成功'}`)
    state.showOperateModal = false
    loadData()
  })
}

// 非社长编辑自己的资料
function onEdit (club_id, member_id) {
  postMemberProfile({ club_id, member_id, ...state.editForm }).then(() => {
    showToast('保存成功')
    refresh()
    state.showOperateModal = false
  })
}

// 点击审核
function onAudit (item) {
  state.auditCurrentMember = item
  state.showAuditModal = true
}

// 审核
function onAuditHandle (type) {
  postMemberAudit({
    member_id: state.auditCurrentMember?.id,
    status: type
  }).then(() => {
    showToast(`${type ? '已通过' : '已拒绝'}`)
    state.showAuditModal = false
    if (type == 1) {
      state.memberNum++
    }
    loadData()
  })
}

// 全选
function onSelectedAll () {
  state.selectedAll = !state.selectedAll
  // fromType为work时禁用社长  foromType为trend时禁用本人
  const isSelectedAll = state.totalMemberList.filter(v => v.user_id != userInfo.value.id).some(v => !v.selected)
  if (isSelectedAll) {
    state.totalMemberList.forEach(v => {
      if (v.user_id != userInfo.value.id) {
        v.selected = true
      }
    })
  } else {
    state.totalMemberList.forEach(v => {
      v.selected = false
    })
  }
}

// 确认添加成员
function onSubmit () {
  if (selectNum.value == 0) {
    showToast('请选择成员', 'none')
    return
  }
  const members = state.totalMemberList.filter(v => v.selected)
  refreshPrePage('onAccepMember', members)
  setTimeout(() => {
    uni.navigateBack()
  }, 600);
}

function refresh () {
  list.value.onRefresh()
}

function loadData (page) {
  const postMethod = state.tabCurrent == 0 && state.member_position >= 2 ? getMemberAuditLists : getMemberLists
  postMethod(state.club_id).then(res => {
    console.log('成员列表', res.data);
    if (state.tabCurrent == 0 && state.member_position >= 2) {
      list.value.onLoadResult(page ? res.data : []);
    } else {
      const { management, counselor, member } = res.data
      state.management = management
      state.counselor = counselor
      state.member = member
      state.totalMemberList = [...state.management, ...state.counselor, ...state.member]
      if (state.call_ids) {
        state.totalMemberList.forEach(t => {
          state.call_ids.forEach(c => {
            if (t.user_id == c) {
              t.selected = true
            }
          })
        })
      }
      state.selectedAll = !state.totalMemberList.filter(v => v.user_id != userInfo.value.id).some(v => !v.selected)
    }
  })
}

onLoad((options) => {
  console.log('options', options);
  // 从哪个页面进入
  state.fromType = options?.fromType ?? ''
  state.showCheck = options?.showCheck ? JSON.parse(options.showCheck) : false
  state.club_id = options.club_id
  state.member_position = options.member_position
  state.memberNum = options.memberNum
  // 初始化选中回显
  if (options.call_ids) {
    state.call_ids = options.call_ids.split(',')
  }
  loadData;
});
</script>

<style lang="scss" scoped>
.border-avatar {
  border: 6rpx solid #F4AF22;
}

.tag-identity {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  justify-content: center;
  align-items: center;
  min-width: 104rpx;
  padding: 2rpx 16rpx;
  color: #FFFFFF;
  font-size: 20rpx;
}

.label-style {
  padding: 2rpx 10rpx;
  color: #fff;
  font-size: 20rpx;
  margin-right: 16rpx;
  border-radius: 6rpx;

  &3 {
    background-color: #F4AF22;
  }

  &2 {

    background-color: #6FC9E7;
  }

  &1 {
    background-color: #F8DC61;
  }
}

.slot-content {
  position: relative;
  padding: 40rpx;
}

.btn {
  width: 260rpx;
  height: 68rpx;
  line-height: 68rpx;
  text-align: center;
  border-radius: 10rpx;
  font-size: 14px;
}

.btn-remove {
  border: 2rpx solid #F4AF22;
  color: #F4AF22;
}

.btn-manage {
  background-color: #F4AF22;
  color: #fff;
}

.btn-edit {
  background-color: #F4AF22;
  color: #fff;
  width: 560rpx;
}

.btn-audit {
  color: #fff;
  width: 104rpx;
  height: 48rpx;
  line-height: 48rpx;
  text-align: center;
  border-radius: 12rpx;
  background: linear-gradient(-180deg, rgba(244, 174, 32, 1) 0%, rgba(248, 220, 97, 1) 100%);
}

.tab-active {
  background: linear-gradient(-76.14deg, rgba(248, 220, 97, 1) 0%, rgba(244, 174, 32, 1) 100%);
  border: 1px solid #FFFFFF;
  border-radius: 12rpx;
  box-shadow: -1.2246468525851679e-16px 2px 6px 0px rgba(206, 143, 12, 0.3);
  color: #fff;
  font-weight: bold;
}
</style>


